<template>
  <el-card class="box-card" v-loading="loading">
    <div slot="header" class="clearfix">
      <span>图片对比</span>
    </div>
    <el-form
      label-width="120px"
      :rules="rules"
      ref="formLabelAlign"
      :model="formLabelAlign"
    >
      <span>请选择要比对的两张图片:</span>
      <el-form-item label="" prop="carrierImage" ref="carrierImage">
        <el-upload
          class="avatar-uploader"
          :on-change="getFile1"
          :on-remove="removeFile1"
          action="http://localhost:8888/user/upload"
          :on-success="handleAvatarSuccess1"
          :show-file-list="false"
        >
          <div class="originimg" v-if="file1" @click.stop>
            <img :src="file1" alt="" class="avatar" />
            <div class="img-bg">
              <span @click.stop="removeFile1">
                <i class="el-icon-delete"></i>
              </span>
            </div>
          </div>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="" prop="carrierImage" ref="carrierImage">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8888/user/upload"
          :on-change="getFile2"
          :on-success="handleAvatarSuccess2"
          :show-file-list="false"
        >
          <div class="originimg" v-if="file2" @click.stop>
            <img :src="file2" alt="" class="avatar" />
            <div class="img-bg">
              <span @click.stop="removeFile2">
                <i class="el-icon-delete"></i>
              </span>
            </div>
          </div>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-dialog
        :visible.sync="infoVisible"
        width="500px"
        title="对比结果"
        center
      >
        <div>{{result}}</div>
      </el-dialog>
      <el-form-item class="submitButton">
        <el-button type="primary" @click="submitForm"
        >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "Insert",
  data() {
    var encryptValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请先进行加密"));
      } else {
        callback();
      }
    };
    return {
      file1:'',
      file2:'',
      upload_image1:undefined,
      upload_image2:undefined,
      isEmbed: 0, //嵌入
      formLabelAlign: {
        algorithm: "1", //算法选择 1，2
        encrypt: false, // 是否加密
        carrierImage: "", //载体图像
        secretData: "", //秘密信息
      },
      result:'',
      infoVisible: false,
      containSecretImage: "", //载密图像
      imageKey: "", //图像密钥
      dataKey: "", //信息密钥
      encryptedImage: "", //加密图像
      carrierEncryptedImage: "", // 载密加密图像
      loading: false,
      dialogImageUrl: "", //嵌入后的图像
      dialogVisible: false , //嵌入后的图像弹窗
      disabled: false, //上传按钮是否禁用
      rules: {
        secretData: [
          { required: true, message: "请输入秘密信息", trigger: "blur" },
        ],
        encrypt: [{ validator: encryptValid, trigger: "change" }],
        carrierImage: [
          { required: true, message: "请上传图片", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    const urlList = document.querySelector(".el-upload-list");
    console.log(urlList);
  },
  methods: {
    getFile1(file,fileList){
      this.upload_image1 = file.raw
    },
    getFile2(file,fileList){
      this.upload_image2= file.raw
    },
    // 下载
    handleDownload() {
      const name = "嵌入后的图片";
      const url = this.formLabelAlign.carrierImage;
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        var a = document.createElement("a");
        a.download = name;
        a.href = url;
        a.click();
      };
      image.src = url;
    },

    // 移除文件
    removeFile1(){
      this.file1 = "";
    },
    removeFile2(){
      this.file2 = "";
    },

    // 上传文件
    handleAvatarSuccess1(res, file, fileList) {
      if (res.url) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.file1 = res.url
        // this.formLabelAlign.carrierImage = res.url;
        // this.oldCarrierImage = this.formLabelAlign.carrierImage
        // this.$refs.carrierImage.clearValidate();
      }
    },
    // 上传文件
    handleAvatarSuccess2(res, file, fileList) {
      if (res.url) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.file2 = res.url
      }
    },
    // 加密图像
    encryptImg(val) {
      if (val) {
        console.log(this.formLabelAlign.carrierImage,"11111111111111111111111111111")
        this.loading = true;
        this.$axios
          .post("http://127.0.0.1:7777/encryption", {carrierImage:this.formLabelAlign.carrierImage},{responseType: 'blob'})
          .then((res) => {
            console.log(res,2222222)
            if (res.data) {
              let blob = new Blob([res.data], { type: res.headers['content-type']});
              // let url = URL.createObjectURL(blob);
              this.formLabelAlign.carrierImage = URL.createObjectURL(blob)

              var formData = new FormData();
              formData.append('file', blob, `${+new Date()}加密图片.png`);

              // 发送 HTTP POST 请求到 Java 服务
              fetch('http://localhost:8888/user/upload',{
                method: 'POST',
                body: formData
              }).then(response => response.json())
                .then(res => {
                  // 处理响应
                  console.log(res, '加密后的图像')
                  this.loading = false;
                  this.encryptedImage = res.url
                  console.log('File uploaded successfully');
                })
                .catch(error => {
                  // 处理错误
                  console.error('Error uploading file:', error);
                });

            }
          });
      }
    },
    // 提交
    submitForm() {
      var formData = new FormData();
      formData.append('file1', this.upload_image1);
      formData.append('file2', this.upload_image2);
      console.warn('file1', this.upload_image1)
      this.$axios
        .post("http://127.0.0.1:7777/compareImages",formData)
        .then((res) => {
          console.log(res)
          this.result = res.data
          this.infoVisible = true
          this.$message({
            message: res.data,
            type: "success",
          });
          setTimeout(() => {
            this.infoVisible = true;
          }, 1000);
        })
    },
  },
};
</script>

<style scoped>
.el-form{
  display: flex;
}
.el-button {
  border: none;
}

/deep/.el-form-item__content{
  margin-left: 12px!important;
}
.box-card {
  width: 1000px;
  min-height: 550px;
  background: #fff;
  padding: 20px;
  border: 1px solid #ebebeb;
  position: relative;
  border-radius: 3px;
  box-shadow: 0 0 8px rgba(232, 237, 250, 0.6),
  0 2px 4px 0 rgba(232, 237, 250, 0.5);
}
.submitButton {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  margin-bottom: 0;
}
.clearfix {
  text-align: center;
  font-size: 24px;
  font-weight: 500;
}
/deep/ .el-dialog__body {
  text-align: center;
}

/deep/.el-cards .el-card__body {
  display: flex;
  align-items: center;
  flex-direction: column;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.originimg {
  position: relative;
}
.img-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-icon-delete,
.el-icon-download {
  display: none;
}
.img-bg:hover {
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.img-bg:hover .el-icon-delete,
.img-bg:hover .el-icon-download {
  display: block;
  font-size: 36px;
  color: #fff;
}
</style>
